<template>
  <a-drawer
      :title="this.dataForm.id ? '编辑评分' : '添加评分'"
      width="800"
      placement="right"
      :closable="false"
      :visible="visible"
      :after-visible-change="afterVisibleChange"
      @close="onClose">
    <a-spin :spinning="loading">
      <a-form-model ref="dataForm" :model="dataForm" :rules="validatorRules">
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="评分名称" prop="assessDetail">
          <a-textarea placeholder="请输入题目名称" v-model="dataForm.assessDetail" :auto-size="{ minRows: 3, maxRows: 5 }" />
        </a-form-model-item>

        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="选项">
          <a-table bordered :data-source="dataSource" :columns="columns" size="small" :pagination="false" :showHeader="false">
            <template slot="point" slot-scope="text, record">
              <editable-cell :text="text" :type="'text'" @change="onCellChange(record.key, 'point', $event)" />
            </template>
            <template slot="raction" slot-scope="text, record">
              <a-row type="flex" align="middle" style="flex-wrap: nowrap">
                <div>得分: </div>
                <editable-cell :text="text" :type="'number'" @change="onCellChange(record.key, 'raction', $event)" style="width: 80%"/>
              </a-row>
            </template>
            <template slot="operation" slot-scope="text, record">
              <a-popconfirm
                  v-if="dataSource.length"
                  title="Sure to delete?"
                  @confirm="() => onDelete(record.key)">
                <a href="javascript:;">Delete</a>
              </a-popconfirm>
            </template>
          </a-table>
          <a-form-model-item>
            <a-button type="dashed" style="width: 60%" @click="handleAdd">
              <a-icon type="plus" />
              Add field
            </a-button>
          </a-form-model-item>
        </a-form-model-item>
      </a-form-model>
      <div class="anty-form-btn">
        <a-button @click="emptyCurrForm" type="default" htmlType="button" icon="sync">重置</a-button>
        <a-button @click="submitCurrForm" type="primary" htmlType="button" icon="form">保存</a-button>
      </div>
    </a-spin>
  </a-drawer>
</template>

<script>
import { httpActions } from '@/api/manage'

const EditableCell = {
  template: `
    <div class="editable-cell">
    <div v-if="editable" class="editable-cell-input-wrapper">
      <a-input :value="value" v-if="type === 'text'" @change="handleChange" @pressEnter="check" style="width: 80%" />
      <a-input-number :value="value" v-else-if="type === 'number'" @change="handleChange2" @pressEnter="check" />
      <a-icon
          type="check"
          class="editable-cell-icon-check"
          @click="check" />
    </div>
    <div v-else class="editable-cell-text-wrapper">
      {{ value || ' ' }}
      <a-icon type="edit" class="editable-cell-icon" @click="edit" />
    </div>
    </div>
  `,
  props: {
    text: String,
    type: {
      type: String,
      required: false,
      default: 'text'
    },
  },
  data() {
    return {
      value: this.text,
      editable: false,
    };
  },
  methods: {
    handleChange(e) {
      const value = e.target.value;
      this.value = value;
    },
    handleChange2(e) {
      const value = e;
      this.value = value.toString();
    },
    check() {
      this.editable = false;
      this.$emit('change', this.value);
    },
    edit() {
      this.editable = true;
    },
  },
};
export default {
  name: "title-form",
  components: {
    EditableCell,
  },
  data () {
    return {
      visible: false,
      loading: false,
      dataForm: {
        id: '',
        assessDetail: '',
        ratingQuestion: '',
        ratingScore: '',
      },
      defaultDataForm: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      dataSource: [
        // {
        //   key: '0',
        //   point: '10分（优秀）',
        //   raction: '10',
        // },
        // {
        //   key: '1',
        //   point: '9分（良好）',
        //   raction: '9',
        // },
      ],
      defaultDataSource: [],
      columns: [
        {
          title: '#',
          dataIndex: '',
          customRender: function (t, r, index) {
            return '选项 ' + parseInt(index + 1)
          }
        },
        {
          title: 'point',
          dataIndex: 'point',
          scopedSlots: { customRender: 'point' },
        },
        {
          title: 'raction',
          dataIndex: 'raction',
          scopedSlots: { customRender: 'raction' },
        },
        {
          title: 'operation',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      url: {
        save: '/dimension/insertDimensions',
        edit: '/dimension/updateDimension',
      }
    }
  },
  computed: {
    validatorRules () {
      return {
        assessDetail: [
          { required: true, message: '请输入问卷名称!', trigger: 'blur' }
        ],
      }
    },
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate(['assessDetail'])
        this.dataSource = []
        if (this.dataForm.id) {
          var items = this.dataForm.ratingQuestion.split(',')
          var scores = this.dataForm.ratingScore.split(',')
          for (let i = 0; i < items.length; i++) {
            this.dataSource[i] = {
              key: i,
              point: items[i],
              raction: scores[i],
            }
          }
          this.defaultDataForm = Object.assign({}, this.dataForm)
          this.defaultDataSource = Object.assign([], this.dataSource)
        }
      })
    },
    emptyCurrForm () {
      this.dataForm = Object.assign({}, this.defaultDataForm)
      this.dataSource = Object.assign([], this.defaultDataSource)
    },
    submitCurrForm () {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.loading = true
          console.log('this.dataSource', this.dataSource)
          this.dataForm.ratingQuestion = this.dataSource.map(res => res.point).toString()
          this.dataForm.ratingScore = this.dataSource.map(res => res.raction).toString()
          console.log('this.dataForm', this.dataForm)
          let method
          let url
          if (this.dataForm.id) {
            method = 'post'
            url = this.url.edit
          } else {
            method = 'post'
            url = this.url.save
          }
          httpAction(url, this.dataForm, method).then((res) => {
            if (res.success) {
              this.loading = false
              this.$message.success({
                content: '保存成功!',
                duration: 1,
                onClose: () => {
                  this.onClose()
                  this.$emit('load')
                }
              })
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    afterVisibleChange () {
    },
    onClose () {
      this.visible = false
      this.dataForm = {}
    },
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource];
      const target = dataSource.find(item => item.key === key);
      if (target) {
        target[dataIndex] = value;
        this.dataSource = dataSource;
      }
    },
    onDelete(key) {
      const dataSource = [...this.dataSource];
      this.dataSource = dataSource.filter(item => item.key !== key);
    },
    handleAdd() {
      const { dataSource } = this;
      const newData = {
        key: dataSource.length,
        point: '',
        raction: '',
      };
      this.dataSource = [...dataSource, newData];
    },
  }
}
</script>

<style scoped>

</style>
